package util

import (
	"fmt"
	"github.com/topfreegames/pitaya/constants"
	"github.com/topfreegames/pitaya/session"
	"strconv"
	"time"
)

func Now() int64 {
	return time.Now().UnixNano() / 1e6
}

func NowMonth(now time.Time) int {
	v,err := strconv.ParseInt(now.Format("01"),10,32)
	if err != nil {
		return 0
	}

	return int(v)
}

/**
字符串转int64
 */
func CastLong(s string) int64 {
	r,err := strconv.ParseInt(s,10,64)
	if err != nil {
		return 0
	}

	return r
}

func GetRetRoute(route string) string {
	return fmt.Sprintf("%s_ret",route)
}

func GetAccountIdFromSession(s *session.Session) (int64,error) {
	if len(s.UID()) == 0 {
		return 0,constants.ErrNoUIDBind
	}

	accountId,err := strconv.ParseInt(s.UID(),10,64)
	if err != nil {
		return 0,err
	}

	return accountId,nil
}

func IntToByteArray(value int) []byte {
	arr := make([]byte,0)
	for i:= 0;i<4;i++ {
		arr = append(arr,byte(value >> 8*i)&0xFF)
	}

	return arr
}

func ByteArrayToInt(bytes []byte) int32 {
	rs := 0
	for i:= 0;i<len(bytes);i++{
		v := bytes[i]
		rs |= int(v) << 8*i
	}
	return int32(rs)
}

func ByteArrayToIntArray(bytes []byte) []int32 {
	rs := []int32{}
	length := len(bytes)
	for i:=0;i<length; {
		value := 0

		for index := 0;index<4&&i<length;index++{
			v := bytes[i]
			value |= int(v) << 8*index
			i ++
		}

		rs = append(rs,int32(value))
	}

	return rs
}
